namespace app\controller;

use think\Request;
use app\model\Paper;
use app\model\ExamRecord;

class Exam
{
    // 开始考试
    public function start(Request $request)
    {
        $paperId = $request->param('id');
        $userId = session('user_id');
        
        // 检查是否已有记录
        $record = ExamRecord::where('user_id', $userId)
            ->where('paper_id', $paperId)
            ->where('status', 0)
            ->find();
            
        if (!$record) {
            $paper = Paper::find($paperId);
            $record = ExamRecord::create([
                'user_id' => $userId,
                'paper_id' => $paperId,
                'start_time' => date('Y-m-d H:i:s'),
                'answers' => '{}',
                'status' => 0
            ]);
        }
        
        return view('exam/index', [
            'record' => $record,
            'paper' => $paper
        ]);
    }

    // 提交答案
    public function submit(Request $request)
    {
        $recordId = $request->post('record_id');
        $answers = $request->post('answers');
        $record = ExamRecord::find($recordId);
        
        // 防止重复提交
        if ($record->status == 1) {
            return json(['code'=>1, 'msg'=>'请勿重复提交']);
        }
        
        // 更新答案
        $record->answers = json_encode($answers);
        $record->end_time = date('Y-m-d H:i:s');
        $record->duration = time() - strtotime($record->start_time);
        $record->status = 1;
        
        // 自动判分 (简答题需手动评分)
        $record->score = $this->calculateScore($record);
        $record->save();
        
        return json(['code'=>0, 'msg'=>'提交成功', 'score'=>$record->score]);
    }
    
    // 自动评分逻辑
    private function calculateScore($record)
    {
        $score = 0;
        $paper = Paper::find($record->paper_id);
        $answers = json_decode($record->answers, true);
        $questions = QuestionModel::whereIn('id', explode(',', $paper->question_ids))->select();
        
        foreach ($questions as $q) {
            if (!isset($answers[$q->id])) continue;
            
            $userAnswer = $answers[$q->id];
            switch ($q->type) {
                case 1: // 填空
                    $correct = trim($userAnswer) === trim($q->answer);
                    break;
                case 2: // 单选
                    $correct = $userAnswer == $q->answer;
                    break;
                case 3: // 多选
                    sort($userAnswer);
                    $correctAnswer = explode(',', $q->answer);
                    sort($correctAnswer);
                    $correct = $userAnswer == $correctAnswer;
                    break;
                case 4: // 判断
                    $correct = $userAnswer == $q->answer;
                    break;
                case 5: // 简答 (不自动评分)
                default:
                    $correct = false;
            }
            
            if ($correct) $score += $q->score;
        }
        
        return $score;
    }
}